package com.example.exam.ZhangFengHua;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

import com.example.exam.R;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;

import static androidx.constraintlayout.widget.Constraints.TAG;

public class Linepm extends Fragment {
    @BindView(R.id.pm_line)
    LineChart pmLine;
    private List<Pmbook_list> pmbook_lists=new ArrayList<>();
    private List<PmBook> pmBooks=new ArrayList<>();
    private ArrayList<Entry> entries=new ArrayList<>();
    public Linepm() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_linepm, container, false);
        ButterKnife.bind(this,view);
        LitePal.getDatabase();
        initys();
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable,3000);
        return view;
    }
    private interface BlogService{
        @GET("getAirCondition")
        Call<ResponseBody>getlog();
    }
    String name[]={"0","3","6","9","12","15"};
    private Handler handler=new Handler();
    private  Runnable runnable=new Runnable() {
        @Override
        public void run() {
            initdata1();
            pmbook_lists=new ArrayList<>();
            handler.postDelayed(this,3000);
        }
    };
    private void initys(){
        //设置图例
        pmLine.animateXY(1000,1000);
        //隐藏图例
        Legend legend=pmLine.getLegend();
        legend.setEnabled(false);
        //隐藏英文
        pmLine.setDescription(null);
        //左边y轴
        YAxis yAxis1=pmLine.getAxisLeft();
        yAxis1.setDrawGridLines(false);
        yAxis1.setEnabled(true);
        yAxis1.setAxisMinimum(0);
        yAxis1.setAxisMaximum(200);
        //隐藏右边y轴
        YAxis yAxis=pmLine.getAxisRight();
        yAxis.setEnabled(false);
        //设置x轴
        XAxis xAxis=pmLine.getXAxis();
        xAxis.setDrawGridLines(false);
        //设置x轴的方向
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //自定义x轴坐标
        xAxis.setValueFormatter(new IndexAxisValueFormatter(){
            public String getAxisLabel(float value, AxisBase axisBase){
                return name[(int) value];
            }
        });
    }
    private void initdata1(){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        BlogService service=retrofit.create(BlogService.class);
        Call<ResponseBody>call=service.getlog();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
             Gson gson=new Gson();
                try {
                    Pmbook_list carlist=gson.fromJson(response.body().string(),Pmbook_list.class);
                    pmbook_lists.add(carlist);
                    initview();
                    initData();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
    private void initData(){
        entries=new ArrayList<>();
        pmBooks=LitePal.findAll(PmBook.class);
        int x=1;
        for (PmBook pmBook:pmBooks){
            entries.add(new Entry(x,Float.parseFloat(pmBook.getPm2_5())));
            x++;
        }
        /**************判断图中是否已有LineDataSet，如果有就删除，重新创建加载****************/
        if (pmLine.getData() != null &&
                pmLine.getData().getDataSetCount() > 0) {
            pmLine.getData().removeDataSet(0);
        }
        LineDataSet set=new LineDataSet(entries,"五天里的PM2.5指数");
//        for (PmBook pmBook:pmBooks){
//            if (x>100){
//                set.setCircleColors(Color.RED);
//            }else {
//                set.setCircleColors(Color.GREEN);
//            }
//        }
//
//        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
//        dataSets.add(set); // add the datasets
//        LineData data = new LineData(dataSets);
//        /**************设置数据，并移动到最新点的位置****************/
//        pmLine.setData(data);
//        pmLine.moveViewToX(set.getEntryCount()-1);
//        set.setDrawIcons(false);
        //给折线图加颜色是3.1.0必须要加的
        set.setColor(Color.BLACK);
        LineData set1=new LineData(set);
        pmLine.setData(set1);
        pmLine.invalidate();
    }
    private void initview() {
        PmBook book=new PmBook();
        book.setPm2_5(pmbook_lists.get(0).get_$Pm25298()+"");
        book.save();
       List<PmBook> books= LitePal.findAll(PmBook.class);
       int all=books.size();
       if (all>5){
           PmBook firstpmbook=LitePal.findFirst(PmBook.class);
           LitePal.deleteAll(PmBook.class,"id=?",firstpmbook.getId()+"");
       }
    }
}
